package com.hpe.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hpe.common.Const;
import com.hpe.dao.*;
import com.hpe.pojo.*;
import com.hpe.service.SClassService;
import com.hpe.util.ResponseCode;
import com.hpe.util.ServerResponse;
import com.hpe.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:TangWenhao
 * @Description:
 * @Date:19:05 2017/9/25
 */
@Service
public class SClassServiceImpl implements SClassService {

    @Autowired
    private SClassMapper sClassMapper;

    @Autowired
    private GroupMapper groupMapper;

    @Autowired
    private StudentInfoMapper studentInfoMapper;

    @Autowired
    private ScoreMapper scoreMapper;

    @Autowired
    private ClassHistoryMapper classHistoryMapper;

    @Autowired
    private ClassNumMapper classNumMapper;

    @Autowired
    private ClassTeacherMapper classTeacherMapper;

    private Logger logger = LoggerFactory.getLogger(SClassServiceImpl.class);

    @Override
    @Transactional
    public ServerResponse<String> saveClass(SClass stu) {
        int count = sClassMapper.ifExistOther(Const.ClassState.ONSCHOOL, stu.getOther());
        if (count > 0) {
            return ServerResponse.createByErrorMsg("该备注已经存在");
        }
        stu.setState(Const.ClassState.ONSCHOOL);
        int result = sClassMapper.insert(stu);
        if (result <= 0) {
            return ServerResponse.createByErrorMsg("添加班级失败");
        }
        //更新班级人数表记录
        ClassNum classNum = new ClassNum();
        //增加班级初始值为0人
        classNum.setcNum(0);
        classNum.setcId(stu.getId());
        //执行班级人数表插入操作
        int result1 = classNumMapper.insertSelective(classNum);
        if (result1 > 0) {
            return ServerResponse.createBySuccessMsg("添加班级成功");

        }
        return ServerResponse.createByErrorMsg("添加班级失败");
    }

    @Override
    public ServerResponse<PageInfo> getClassesByState(int state, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ClassDirectionVo> allClass = sClassMapper.getClassVos(state);
        PageInfo pageInfo = new PageInfo(allClass);
        return ServerResponse.createBySuccess(pageInfo);
    }

    public List<ClassDirectionVo> getCurrentClasss() {
        return sClassMapper.getClassVos(1);
    }

    @Override
    public ServerResponse<PageInfo> getAllClassScore(String className, String teacherName, String courseName, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ClassScoreVO> allClassScore = scoreMapper.getAllClassAvgForExam(className, teacherName, courseName);
        PageInfo pageInfo = new PageInfo(allClassScore);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse<PageInfo> getClassesByTeacher(int teaId, int state, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<SClass> allClass = sClassMapper.getClassesByTeacher(teaId, state);
        PageInfo pageInfo = new PageInfo(allClass);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse<String> updateClassOther(SClass sClass) {
        int count = sClassMapper.ifExistOther(Const.ClassState.ONSCHOOL, sClass.getOther());
        if (count > 0) {
            return ServerResponse.createByErrorMsg("该备注已经存在");
        }
        //判断新的备注是否为空
        if (StringUtils.isBlank(sClass.getOther())) {
            return ServerResponse.createByErrorCodeMsg(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        int result = sClassMapper.updateOther(sClass.getOther(), sClass.getId());
        if (result > 0) {
            return ServerResponse.createBySuccessMsg("修改备注成功");
        }
        return ServerResponse.createByErrorMsg("修改备注失败");
    }

    @Override
    public ServerResponse<String> updateClassState(SClass sClass) {
        SClass theClass = sClassMapper.selectByPrimaryKey(sClass.getId());

        if (Const.ClassState.ONSCHOOL == theClass.getState()) {
            if (theClass.getSpare() != null) {
                if (theClass.getSpare().equals("1")) {
                    return ServerResponse.createByErrorMsg("该班级已同方向绑定，无法注销");
                }
            }
            int result = sClassMapper.updateState(Const.ClassState.LEVEL, sClass.getId());
            if (result > 0) {
                return ServerResponse.createBySuccessMsg("该班级已经成功注销");
            } else {
                return ServerResponse.createByErrorMsg("该班级注销失败");
            }
        }
        return ServerResponse.createByErrorMsg("该班级已经是注销状态");
    }

    @Override
    public ServerResponse<List<SClass>> getClasses(int type) {
        List<SClass> sClasses = sClassMapper.getClasses(Const.ClassState.ONSCHOOL, type);
        if (sClasses == null) {
            ServerResponse.createByErrorMsg("查询班级失败");
        }
        return ServerResponse.createBySuccess(sClasses);
    }

    @Override
    public ServerResponse<List<SClass>> getClasses() {
        List<SClass> sClasses = sClassMapper.getClassesNotType(Const.ClassState.ONSCHOOL);
        if (sClasses == null) {
            ServerResponse.createByErrorMsg("查询班级失败");
        }
        return ServerResponse.createBySuccess(sClasses);
    }

    @Override
    public SClass findStuClassById(int id) {
        return sClassMapper.findStuClassById(id);
    }

    @Override
    public SClass selectByPrimaryKey(Integer id) {
        return sClassMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<SClass> selectByType(Integer type) {
        return sClassMapper.getClassListByType(type);
    }

    @Override
    public ServerResponse<List<SClass>> getSClassListByType(Integer type) {
        List<SClass> classes = sClassMapper.getClassIdAndNameByType(type);
        if (classes.size() == 0) {
            return ServerResponse.createByErrorMsg("没有该方向的班级");
        }
        return ServerResponse.createBySuccess(classes);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse<String> divideClassBySCurve(String classIds, int groupId) {
        String[] classIdArray = classIds.split(",");
        int classCount = classIdArray.length;
        Map<Integer, Integer> reduceClassNumMap = new HashMap<Integer, Integer>();
        //插入班级人数表的时候使用
        int[] classNum = new int[classCount];

        //获得学生的数量
        int stuCount = groupMapper.getStudentCountByGroupId(groupId);
        try {
            if (stuCount == 0) {
                throw new Exception("当前归档没有学生，请归档后再进行操作");
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            return ServerResponse.createByErrorMsg(e.getMessage());
        }

        //获得学生的id和rank
        List<Group> groups = groupMapper.getStudentIdsAndRankByGroupId(groupId);
        try {
            if (stuCount != groups.size()) {
                throw new Exception("后台查询出错，请重新进行操作");
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            return ServerResponse.createByErrorMsg(e.getMessage());
        }
        List<ClassHistory> histories = new ArrayList<>();
        int j = 0;
        boolean flag = true;
        for (int i = 0; i < stuCount; i++) {
            Group group = groups.get(i);

            //当前的学生id
            Integer currentStuId = group.getsId();
            //当前的班级id
            Integer currentClassId = Integer.parseInt(classIdArray[j]);
            StudentInfo studentInfo = studentInfoMapper.selectByPrimaryKey(group.getsId());
            //创建班级历史记录
            ClassHistory history = new ClassHistory();
            history.setClassId(currentClassId);
            history.setsId(currentStuId);
            history.setSpare(studentInfo.getSpare());
            Integer oldClass = Integer.parseInt(studentInfo.getSpare());
            if(reduceClassNumMap.containsKey(oldClass)){
                Integer num = reduceClassNumMap.get(oldClass);
                if(num != 0) {
                    reduceClassNumMap.put(oldClass, num - 1);
                }
            }else{
                ClassNum myClassNum = classNumMapper.selectLastClassNumById(oldClass);
                if(myClassNum != null) {
                    if(myClassNum.getcNum() == 0){
                        reduceClassNumMap.put(oldClass, 0);
                    }else {
                        reduceClassNumMap.put(oldClass, myClassNum.getcNum() - 1);
                    }
                }else {
                    reduceClassNumMap.put(oldClass,0);
                }
            }
            try {
                if (studentInfo.getName() == null) {
                   throw new Exception("查询学生姓名时出现错误，请重新分班");
                }
            }catch (Exception e){
                logger.error(e.getMessage());
                return ServerResponse.createByErrorMsg(e.getMessage());
            }
            history.setsName(studentInfo.getName());

            int count = studentInfoMapper.updateStudentSpare(currentStuId, currentClassId);

            try {
                if (count == 0) {
                   throw new Exception("学生班级更新时出现错误，请重新分班");
                }
            }catch (Exception e){
                logger.error(e.getMessage());
                return ServerResponse.createByErrorMsg(e.getMessage());
            }
            classNum[j] += 1;

            if (flag) {
                if (++j == classCount) {
                    flag = false;
                    j--;
                }
            } else {
                if (--j == -1) {
                    flag = true;
                    j++;
                }
            }
            histories.add(history);
        }

        Map<Integer, Integer> classNumMap = new HashMap<Integer, Integer>();
        for (int k = 0; k < classCount; k++) {
            classNumMap.put(Integer.parseInt(classIdArray[k]), classNum[k]);
        }
        try {
            int historyCount = classHistoryMapper.insertList(histories);
            if (historyCount < histories.size()) {
               throw new Exception("有学生更新未成功");
            }
            int numCount = classNumMapper.insertMap(reduceClassNumMap);
            if(numCount < reduceClassNumMap.size()){
                throw new Exception("存在学生班级信息未更新成功");
            }
            numCount = classNumMapper.insertMap(classNumMap);
            if (numCount < classNumMap.size()) {
                throw new Exception("存在学生班级信息未更新成功");
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            return ServerResponse.createByErrorMsg(e.getMessage());
        }
        return ServerResponse.createBySuccessMsg("更新成功");
    }


    /**
     * @param classId
     * @param pageNum
     * @param pageSize
     * @Author:HouPeng
     * @Description: 根据班级id获取当前班级的所有学生及新班级
     * @Date:14:56 2017/10/17
     * @param:classId 班级id
     * @return:
     */
    @Override
    public ServerResponse<PageInfo<ClassStuVo>> getAllStuVoByClassId(Integer classId, Integer pageNum, Integer pageSize) {
        // 设置分页信息
        PageHelper.startPage(pageNum, pageSize);
        List<ClassStuVo> classStuVos = classHistoryMapper.getAllStuVoByClassId(classId);
        // 取查询结果
        PageInfo<ClassStuVo> pageInfo = new PageInfo<>(classStuVos);
        //返回成功信息
        return ServerResponse.createBySuccess(pageInfo);
    }

    /**
     * @return true 存在 / false 不存在
     * @description 删除方向时检索是否有该方向的班级存在
     * @author Fujt
     * @date 2017/10/20 11:17
     */
    @Override
    public boolean findByTypeExistOrNot(int type) {
        return sClassMapper.findByTypeExistOrNot(type) != null;
    }

    @Override
    public Integer addClassDirection(SClass sClass) {
        sClass.setSpare("1");
        Integer integer = sClassMapper.updateByPrimaryKeySelective(sClass);
        return integer;
    }

    @Override
    public Integer deleteClassDirection(SClass sClass) {
        sClass.setSpare(null);
        Integer integer = sClassMapper.updateByPrimaryKey(sClass);
        return integer;
    }

    @Override
    public SClass getSClass(int id) {
        return sClassMapper.selectByPrimaryKey(id);
    }

    @Override
    public SClass getDirectionClass(int id) {
        return sClassMapper.selectDirectionClass(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse<String> divideClassByThree(DivideClassVo divideClassVo) {
        //获得当前group中的总人数
        int count = groupMapper.getStudentCountByGroupId(divideClassVo.getGroupId());
        Map<Integer, Integer> reduceClassNumMap = new HashMap<Integer, Integer>();
        //获得要被分班的信息
        List<Group> groups = groupMapper.getStudentIdsAndRankByGroupId(divideClassVo.getGroupId());

        //创建结果集
        List<ClassHistory> classHistories = new ArrayList<>(count);
        Map<Integer, Integer> classNumMap = new HashMap<Integer, Integer>();
        int[] classNum = new int[groups.size()];
        String[] oneId, twoId, threeId;
        //把三个阶段的班级id各自分割开
        oneId = divideStringToArray(divideClassVo.getOneId(), divideClassVo.getOneStu());
        twoId = divideStringToArray(divideClassVo.getTwoId(), divideClassVo.getTwoStu());
        threeId = divideStringToArray(divideClassVo.getThreeId(), divideClassVo.getThreeStu());
        //第一阶段直线
        if (divideClassVo.getOneStu() != 0) {
            if (divideClassVo.getOneType().equals("line")) {
                int stuNum = divideClassVo.getOneStu();
                int oneCount = 0;
                int[] classNumArr = new int[oneId.length];
                //获得每个班的人数
                if (stuNum % oneId.length > 0) {
                    oneCount = stuNum / oneId.length + 1;
                } else {
                    oneCount = stuNum / oneId.length;
                }

                int j = 0;
                //开始直线分班
                for (int i = 0; i < stuNum; i++) {
                    Group group = groups.get(i);
                    int stuId = group.getsId();
                    int classId = Integer.parseInt(oneId[j]);
                    StudentInfo studentInfo = studentInfoMapper.selectByPrimaryKey(stuId);
                    //组装history
                    ClassHistory history = new ClassHistory();
                    history.setsId(stuId);
                    history.setClassId(classId);
                    history.setSpare(studentInfo.getSpare());
                    Integer oldClass = Integer.parseInt(studentInfo.getSpare());
                    if(reduceClassNumMap.containsKey(oldClass)){
                        Integer num = reduceClassNumMap.get(oldClass);
                        if(num != 0) {
                            reduceClassNumMap.put(oldClass, num - 1);
                        }
                    }else{
                        ClassNum myClassNum = classNumMapper.selectLastClassNumById(oldClass);
                        if(myClassNum != null) {
                            if(myClassNum.getcNum() == 0){
                                reduceClassNumMap.put(oldClass, 0);
                            }else {
                                reduceClassNumMap.put(oldClass, myClassNum.getcNum() - 1);
                            }
                        }else {
                            reduceClassNumMap.put(oldClass,0);
                        }
                    }
                    if (null == studentInfo.getName()) {
                        return ServerResponse.createByErrorMsg("查询出错");
                    }
                    history.setsName(studentInfo.getName());

                    int updateCount = studentInfoMapper.updateStudentSpare(stuId, classId);
                    if (updateCount == 0) {
                        return ServerResponse.createByErrorMsg("学生班级更新时出现错误，请重新分班");
                    }
                    classNumArr[j]++;
                    //如果当前班级人数够了，就开始进行下一个班级的分班
                    if ((i + 1) % oneCount == 0) {
                        j++;
                    }
                    classHistories.add(history);
                }
                for (int i = 0; i < classNumArr.length; i++) {
                    classNumMap.put(Integer.parseInt(oneId[i]), classNumArr[i]);
                }
            } else {
                int j = 0;
                boolean flag = true;
                int[] classNumArr = new int[oneId.length];
                for (int i = 0; i < divideClassVo.getOneStu(); i++) {
                    Group group = groups.get(i);

                    //当前的学生id
                    Integer currentStuId = group.getsId();
                    //当前的班级id
                    Integer currentClassId = Integer.parseInt(oneId[j]);
                    StudentInfo studentInfo = studentInfoMapper.selectByPrimaryKey(currentStuId);
                    //创建班级历史记录
                    ClassHistory history = new ClassHistory();
                    history.setClassId(currentClassId);
                    history.setsId(currentStuId);
                    history.setSpare(studentInfo.getSpare());
                    Integer oldClass = Integer.parseInt(studentInfo.getSpare());
                    if(reduceClassNumMap.containsKey(oldClass)){
                        Integer num = reduceClassNumMap.get(oldClass);
                        if(num != 0) {
                            reduceClassNumMap.put(oldClass, num - 1);
                        }
                    }else{
                        ClassNum myClassNum = classNumMapper.selectLastClassNumById(oldClass);
                        if(myClassNum != null) {
                            if(myClassNum.getcNum() == 0){
                                reduceClassNumMap.put(oldClass, 0);
                            }else {
                                reduceClassNumMap.put(oldClass, myClassNum.getcNum() - 1);
                            }
                        }else {
                            reduceClassNumMap.put(oldClass,0);
                        }
                    }
                    if (studentInfo.getName() == null) {
                        return ServerResponse.createByErrorMsg("查询学生姓名时出现错误，请重新分班");
                    }
                    history.setsName(studentInfo.getName());

                    int updateCount = studentInfoMapper.updateStudentSpare(currentStuId, currentClassId);
                    if (updateCount == 0) {
                        return ServerResponse.createByErrorMsg("学生班级更新时出现错误，请重新分班");
                    }
                    classNumArr[j]++;
                    if (flag) {
                        if (++j == oneId.length) {
                            flag = false;
                            j--;
                        }
                    } else {
                        if (--j == -1) {
                            flag = true;
                            j++;
                        }
                    }
                    classHistories.add(history);
                }
                for (int i = 0; i < classNumArr.length; i++) {
                    classNumMap.put(Integer.parseInt(oneId[i]), classNumArr[i]);
                }
            }
        }
        //第二阶段人是在最后面选择的，即groups.size()-twoId.length - groups.size()的区间
        if (divideClassVo.getTwoStu() != 0) {
            if (divideClassVo.getTwoType().equals("line")) {
                int stuNum = divideClassVo.getTwoStu();
                int twoCount = 0;
                int[] classNumArr = new int[twoId.length];
                if (stuNum % twoId.length > 0) {
                    twoCount = stuNum / twoId.length + 1;
                } else {
                    twoCount = stuNum / twoId.length;
                }
                int j = 0, m = 0;
                for (int i = groups.size() - stuNum, k = groups.size(); i < k; i++) {
                    m++;
                    Group group = groups.get(i);
                    int stuId = group.getsId();
                    int classId = Integer.parseInt(twoId[j]);
                    classNumArr[j]++;
                    StudentInfo studentInfo = studentInfoMapper.selectByPrimaryKey(stuId);
                    ClassHistory history = new ClassHistory();
                    history.setSpare(studentInfo.getSpare());
                    history.setsId(stuId);
                    history.setClassId(classId);
                    Integer oldClass = Integer.parseInt(studentInfo.getSpare());
                    if(reduceClassNumMap.containsKey(oldClass)){
                        Integer num = reduceClassNumMap.get(oldClass);
                        if(num != 0) {
                            reduceClassNumMap.put(oldClass, num - 1);
                        }
                    }else{
                        ClassNum myClassNum = classNumMapper.selectLastClassNumById(oldClass);
                        if(myClassNum != null) {
                            if(myClassNum.getcNum() == 0){
                                reduceClassNumMap.put(oldClass, 0);
                            }else {
                                reduceClassNumMap.put(oldClass, myClassNum.getcNum() - 1);
                            }
                        }else {
                            reduceClassNumMap.put(oldClass,0);
                        }
                    }
                    if (null == studentInfo.getName()) {
                        return ServerResponse.createByErrorMsg("查询出错");
                    }
                    history.setsName(studentInfo.getName());
                    int updateCount = studentInfoMapper.updateStudentSpare(stuId, classId);
                    if (updateCount == 0) {
                        return ServerResponse.createByErrorMsg("学生班级更新时出现错误，请重新分班");
                    }
                    if (m % twoCount == 0) {
                        j++;
                    }

                    classHistories.add(history);
                }
                for (int i = 0; i < classNumArr.length; i++) {
                    classNumMap.put(Integer.parseInt(twoId[i]), classNumArr[i]);
                }
            } else {
                int j = 0;
                boolean flag = true;
                int[] classNumArr = new int[twoId.length];
                for (int i = groups.size() - divideClassVo.getTwoStu(), k = groups.size(); i < k; i++) {
                    Group group = groups.get(i);

                    //当前的学生id
                    Integer currentStuId = group.getsId();
                    //当前的班级id
                    Integer currentClassId = Integer.parseInt(twoId[j]);
                    StudentInfo studentInfo = studentInfoMapper.selectByPrimaryKey(currentStuId);
                    //创建班级历史记录
                    ClassHistory history = new ClassHistory();
                    history.setSpare(studentInfo.getSpare());
                    history.setClassId(currentClassId);
                    history.setsId(currentStuId);
                    Integer oldClass = Integer.parseInt(studentInfo.getSpare());
                    if(reduceClassNumMap.containsKey(oldClass)){
                        Integer num = reduceClassNumMap.get(oldClass);
                        if(num != 0) {
                            reduceClassNumMap.put(oldClass, num - 1);
                        }
                    }else{
                        ClassNum myClassNum = classNumMapper.selectLastClassNumById(oldClass);
                        if(myClassNum != null) {
                            if(myClassNum.getcNum() == 0){
                                reduceClassNumMap.put(oldClass, 0);
                            }else {
                                reduceClassNumMap.put(oldClass, myClassNum.getcNum() - 1);
                            }
                        }else {
                            reduceClassNumMap.put(oldClass,0);
                        }
                    }
                    if (studentInfo.getName() == null) {
                        return ServerResponse.createByErrorMsg("查询学生姓名时出现错误，请重新分班");
                    }
                    history.setsName(studentInfo.getName());

                    int updateCount = studentInfoMapper.updateStudentSpare(currentStuId, currentClassId);
                    if (updateCount == 0) {
                        return ServerResponse.createByErrorMsg("学生班级更新时出现错误，请重新分班");
                    }
                    classNumArr[j]++;
                    if (flag) {
                        if (++j == twoId.length) {
                            flag = false;
                            j--;
                        }
                    } else {
                        if (--j == -1) {
                            flag = true;
                            j++;
                        }
                    }
                    classHistories.add(history);
                }
                for (int i = 0; i < classNumArr.length; i++) {
                    classNumMap.put(Integer.parseInt(twoId[i]), classNumArr[i]);
                }
            }
        }

        if (divideClassVo.getThreeStu() != 0) {
            if (divideClassVo.getThreeType().equals("line")) {
                int threeCount = 0;
                int stuNum = divideClassVo.getThreeStu();
                int[] classNumArr = new int[threeId.length];

                if (stuNum % threeId.length > 0) {
                    threeCount = stuNum / threeId.length + 1;
                } else {
                    threeCount = stuNum / threeId.length;
                }

                int j = 0, m = 0;
                for (int i = divideClassVo.getOneStu(), k = groups.size() - divideClassVo.getTwoStu(); i < k; i++) {
                    m++;
                    Group group = groups.get(i);
                    int stuId = group.getsId();
                    int classId = Integer.parseInt(threeId[j]);
                    StudentInfo studentInfo = studentInfoMapper.selectByPrimaryKey(stuId);
                    ClassHistory history = new ClassHistory();
                    history.setsId(stuId);
                    history.setSpare(studentInfo.getSpare());
                    history.setClassId(classId);
                    Integer oldClass = Integer.parseInt(studentInfo.getSpare());
                    if(reduceClassNumMap.containsKey(oldClass)){
                        Integer num = reduceClassNumMap.get(oldClass);
                        if(num != 0) {
                            reduceClassNumMap.put(oldClass, num - 1);
                        }
                    }else{
                        ClassNum myClassNum = classNumMapper.selectLastClassNumById(oldClass);
                        if(myClassNum != null) {
                            if(myClassNum.getcNum() == 0){
                                reduceClassNumMap.put(oldClass, 0);
                            }else {
                                reduceClassNumMap.put(oldClass, myClassNum.getcNum() - 1);
                            }
                        }else {
                            reduceClassNumMap.put(oldClass,0);
                        }
                    }
                    if (null == studentInfo.getName()) {
                        return ServerResponse.createByErrorMsg("查询出错");
                    }
                    history.setsName(studentInfo.getName());
                    int updateCount = studentInfoMapper.updateStudentSpare(stuId, classId);
                    if (updateCount == 0) {
                        return ServerResponse.createByErrorMsg("学生班级更新时出现错误，请重新分班");
                    }
                    classNumArr[j]++;
                    if (m % threeCount == 0) {
                        j++;
                    }

                    classHistories.add(history);
                }
                for (int i = 0; i < classNumArr.length; i++) {
                    classNumMap.put(Integer.parseInt(threeId[i]), classNumArr[i]);
                }
            } else {
                int j = 0;
                boolean flag = true;
                int stuNum = divideClassVo.getThreeStu();
                int[] classNumArr = new int[threeId.length];
                for (int i = divideClassVo.getOneStu(), k = groups.size() - divideClassVo.getTwoStu(); i < k; i++) {
                    Group group = groups.get(i);

                    //当前的学生id
                    Integer currentStuId = group.getsId();
                    //当前的班级id
                    Integer currentClassId = Integer.parseInt(threeId[j]);
                    StudentInfo studentInfo = studentInfoMapper.selectByPrimaryKey(currentStuId);
                    //创建班级历史记录
                    ClassHistory history = new ClassHistory();
                    history.setSpare(studentInfo.getSpare());
                    history.setClassId(currentClassId);
                    history.setsId(currentStuId);
                    Integer oldClass = Integer.parseInt(studentInfo.getSpare());
                    if(reduceClassNumMap.containsKey(oldClass)){
                        Integer num = reduceClassNumMap.get(oldClass);
                        if(num != 0) {
                            reduceClassNumMap.put(oldClass, num - 1);
                        }
                    }else{
                        ClassNum myClassNum = classNumMapper.selectLastClassNumById(oldClass);
                        if(myClassNum != null) {
                            if(myClassNum.getcNum() == 0){
                                reduceClassNumMap.put(oldClass, 0);
                            }else {
                                reduceClassNumMap.put(oldClass, myClassNum.getcNum() - 1);
                            }
                        }else {
                            reduceClassNumMap.put(oldClass,0);
                        }
                    }
                    if (studentInfo.getName() == null) {
                        return ServerResponse.createByErrorMsg("查询学生姓名时出现错误，请重新分班");
                    }
                    history.setsName(studentInfo.getName());

                    int updateCount = studentInfoMapper.updateStudentSpare(currentStuId, currentClassId);
                    if (updateCount == 0) {
                        return ServerResponse.createByErrorMsg("学生班级更新时出现错误，请重新分班");
                    }
                    classNumArr[j]++;

                    if (flag) {
                        if (++j == threeId.length) {
                            flag = false;
                            j--;
                        }
                    } else {
                        if (--j == -1) {
                            flag = true;
                            j++;
                        }
                    }
                    classHistories.add(history);
                }
                for (int i = 0; i < classNumArr.length; i++) {
                    classNumMap.put(Integer.parseInt(threeId[i]), classNumArr[i]);
                }
            }
        }
        int insertHistoryCount = classHistoryMapper.insertList(classHistories);
        if (insertHistoryCount < groups.size()) {
            return ServerResponse.createByErrorMsg("班级历史插入出现错误");
        }
        int numCount = classNumMapper.insertMap(reduceClassNumMap);

        if(numCount < reduceClassNumMap.size()){
            return ServerResponse.createByErrorMsg("班级记录插入错误");
        }
        int insertNumCount = classNumMapper.insertMap(classNumMap);
        if (insertNumCount < oneId.length + twoId.length + threeId.length) {
            return ServerResponse.createByErrorMsg("班级记录插入错误");
        }
        return ServerResponse.createBySuccessMsg("分班成功");
    }


    private String[] divideStringToArray(String value, int num) {
        String[] result = null;
        if (value != null && num != 0) {
            if (value.contains(",") && value.length() > 1) {
                result = value.split(",");
            } else if (!value.contains(",") && value.length() > 0) {
                result = new String[1];
                result[0] = value;
            }
        }
        if (result == null) {
            result = new String[0];
        }
        return result;
    }
}